package DesginFotmat;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class TimeoutGuardedSuspend {

    public static void main(String[] args) {
        TimeOutGuardedObject guardedObject = new TimeOutGuardedObject();
        new Thread(()->{
            log.debug("等待结果");
            List<String> list =(List<String>) guardedObject.getResponse(30000);
            log.debug("结果大小：{}",list.size());
        },"t1").start();

        new Thread(()->{
            log.debug("执行下载");
            try {
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            List<String> list = new ArrayList<>();
            list.add("你");
            list.add("好");
            guardedObject.complete(list);

        },"t2").start();
    }
}


class TimeOutGuardedObject {
    //结果
    private Object response;

    //获取结果
    //timeout表示要等多久
    public Object getResponse(long timeout) {
        synchronized (this) {
            //开始时间
            long begin = System.currentTimeMillis();
            //经历的时间
            long passedTime = 0;

            //没有结果
            while (response == null) {
                //这一轮循环应该等待的时间
                long waitTime = timeout - passedTime;

                //经历的时间超过了最大等待时间就退出循环
                if(waitTime<=0) {
                    break;
                }
                try {
                    this.wait(waitTime);//避免虚假唤醒导致等待时间变长
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //求得经历时间
                passedTime = System.currentTimeMillis() - begin;
            }
            return response;
        }
    }

    //产生结果
    public void complete(Object response) {
        synchronized (this) {
            //给结果成员变量赋值
            this.response = response;
            this.notifyAll();
        }
    }
}
